package com.sie.demo.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sie.demo.entity.Users;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author liaozhifeng
 * @date 2021/7/29 16:35
 * @Version 1.0
 */
@Slf4j
public class TokenUtil {
    private static final long EXPIRE_TIME= 30*60*1000;
    private static final String TOKEN_SECRET="sie";  //密钥盐

    /**
     * 签名生成
     * @param user
     * @return
     */
    public static String sign(Users user){
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("username", user.getUserName()) //载荷，随便写几个都可以
                    .withExpiresAt(expiresAt)//有效时间
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     * @param token
     * @return
     */
    public static boolean verify(String token){
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
             jwt = verifier.verify(token);
            log.info("认证通过：");
            log.info("username: " + jwt.getClaim("username").asString());
            log.info("过期时间：      " + jwt.getExpiresAt());
            return true;
        } catch (Exception e){
            return false;
        }
    }
}
